package com.overlord.im.commons.jwt;

import io.jsonwebtoken.*;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Date;

public class JwtUtils {
    /**
     * 签发JWT
     *
     * @param id
     * @param subject   可以是JSON数据 尽可能少
     * @param ttlMillis
     * @return String
     * @Author 科帮网
     * @Date 2017年11月24日 2017年11月24日  张志朋  首次创建
     */
    public static String createJWT(String id, String subject, long ttlMillis) throws UnsupportedEncodingException {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setSubject(subject)   // 主题
                .setIssuer("overlord")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate); // 过期时间
        }
        return builder.compact();
    }

    /**
     * 验证JWT
     *
     * @param jwtStr
     * @return
     */
    public static CheckResult validateJWT(String jwtStr) {
        CheckResult checkResult = new CheckResult();
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            checkResult.setSuccess(true);
            checkResult.setClaims(claims);
        } catch (ExpiredJwtException e) {
            checkResult.setErrCode(JwtConstant.JWT_ERRCODE_EXPIRE);
            checkResult.setSuccess(false);
        } catch (SignatureException e) {
            checkResult.setErrCode(JwtConstant.JWT_ERRCODE_FAIL);
            checkResult.setSuccess(false);
        } catch (Exception e) {
            checkResult.setErrCode(JwtConstant.JWT_ERRCODE_FAIL);
            checkResult.setSuccess(false);
        }
        return checkResult;
    }

    public static SecretKey generalKey() throws UnsupportedEncodingException {
        byte[] encodedKey = Base64.encodeBase64(JwtConstant.JWT_SECRET.getBytes("UTF-8"));

        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析JWT字符串
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        //小明失效 10s
        String sc = createJWT("1", "小明", 3000);
        System.out.println(sc);
        System.out.println(validateJWT("eyJhbGciOiJIUzI1NiJ9" +
                ".eyJqdGkiOiIxIiwic3ViIjoi5rWL6K" +
                "-V5ZGYIiwiaXNzIjoib3ZlcmxvcmQiLCJpYXQiOjE2MTYxNDM5NzYsImV4cCI6MTYxNjE0NzU3Nn0" +
                ".ZMt4Fb-CbJj8Pdif84b3d01xf2QYaVT83LpqJbtB4Kg").getErrCode());
        System.out.println(validateJWT("eyJhbGciOiJIUzI1NiJ9" +
                ".eyJqdGkiOiIxIiwic3ViIjoi5rWL6K" +
                "-V5ZGYIiwiaXNzIjoib3ZlcmxvcmQiLCJpYXQiOjE2MTYxNDM5NzYsImV4cCI6MTYxNjE0NzU3Nn0" +
                ".ZMt4Fb-CbJj8Pdif84b3d01xf2QYaVT83LpqJbtB4Kg").getClaims().getId());
        //Thread.sleep(3000);
        System.out.println(validateJWT(sc).getClaims());
    }
}
